package net.myspring.common.utils;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * Created by liuj on 2016/10/5.
 */
public class SystemUtils {

    private static Logger logger = LoggerFactory.getLogger(SystemUtils.class);
    //获取MAC地址的方法
    public static String getMacAddress(){
        InetAddress ia = null;//获取本地IP对象
        //获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
        byte[] mac = null;
        try {
            ia = InetAddress.getLocalHost();
            mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        //下面代码是把mac地址拼装成String
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<mac.length;i++){
            if(i!=0){
                sb.append("-");
            }
            //mac[i] & 0xFF 是为了把byte转化为正整数
            String s = Integer.toHexString(mac[i] & 0xFF);
            sb.append(s.length()==1?0+s:s);
        }

        //把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
    }

    /**
     * 执行CMD命令,并返回String字符串
     */
    public static String executeCmd(String strCmd)  {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("cmd /c " + strCmd);
            InputStream inputStream = process.getInputStream();
            String text = IOUtils.toString(inputStream,"gbk");
            return text;
        } catch (IOException e) {
            logger.error("命令行执行失败：" + strCmd);
        }
        return "";
    }
    /**
     * 连接ADSL
     */
    public static boolean connAdsl(String adslName, String adslUsername, String adslPassword)  {
        logger.info("正在建立连接.");
        String adslCmd = "rasdial " + adslName + " " + adslUsername + " " + adslPassword;
        String tempCmd = executeCmd(adslCmd);
        // 判断是否连接成功
        if (tempCmd.indexOf("已连接") > 0) {
            logger.info("已成功建立连接.");
            return true;
        } else {
            logger.error("建立连接失败:" + tempCmd);
            return false;
        }
    }

    /**
     * 断开ADSL
     */
    public static boolean cutAdsl(String adslName)  {
        String cutAdsl = "rasdial " + adslName + " /disconnect";
        String result = executeCmd(cutAdsl);
        if (result.indexOf("没有连接")!=-1){
            logger.error(adslName + "连接不存在!");
            return false;
        } else {
            logger.info("连接已断开");
            return true;
        }
    }

}
